<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Functions</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="../js/underscore.js"></script>
    <script>
        var word = 'Hello';
        var toUpperCase = _.bind(word.toUpperCase, word);
        //绑定函数
        console.log('toUpperCase() = ' + toUpperCase());
        // 定义偏函数-2的n次方
        var pow2n = _.partial(Math.pow, 2);
        console.log('pow2n(2) = ' + pow2n(2));
        // 定义偏函数-n的立方
        var cube = _.partial(Math.pow, _, 3);
        console.log('cube(2) = ' + cube(2));
        // 定义缓存函数-阶乘函数
        var factorial = _.memoize(
            function (n) {
                console.log('start calculate ' + n + '!...');
                // var s = 1, i = n;
                // while (i > 1) {
                //     s = s * i;
                //     i--;
                // }
                // return s;
                if (n < 2) {
                    return 1;
                }
                return n * factorial(n - 1);
            }
        );
        console.log('factorial(10) = ' + factorial(10));
        console.log('factorial(10) = ' + factorial(10));
        console.log('factorial(9) = ' + factorial(9));
        // 只执行一次的函数
        var onceFunction = _.once(function (value) {
            console.log("excute only once. " + value);
        });
        onceFunction(1);
        onceFunction(2);
        onceFunction(3);

        function delayExcute(msg) {
            console.log(msg);
        }
        _.delay(delayExcute, 2000, 'excute after 2s.');
    </script>
</head>

<body>

</body>

</html>